package org.projsquirrel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;


public class Map extends MapActivity
{
	public Map MyActivity;
	protected MapView myMap;
	private LocationManager locManager;
	private LocationListener locListener;
	private MapController mc;
	private MyItemizedOverlay overlay; 
	
	
 
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		MyActivity = this;
		
		myMap = (MapView) findViewById(R.id.mapview);
		myMap.setBuiltInZoomControls(true);
        mc = myMap.getController();
        mc.setZoom(20);
		initLocationManager();
		
		//set on click listener for the map
        myMap.setOnClickListener(new View.OnClickListener() {			
			public void onClick(View v) {
				
			}
		}); 
		
		//show initial location
		Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if(location == null)
		{
			  AlertDialog.Builder builder = new AlertDialog.Builder(this);
			  builder.setMessage("Your current location could not be resolved, please try again later")
		       .setCancelable(true)
		       .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
			  builder.show();			
		}
		else
		{
			GeoPoint geopoint = new GeoPoint(
					(int) (location.getLatitude() * 1E6), (int) (location
							.getLongitude() * 1E6));
			createAndShowMyItemizedOverlay(geopoint);
		}
	}
 
 
	/**
	 * Initialize the location manager.
	 */
	private void initLocationManager() {
		locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 
		locListener = new LocationListener() {
 
			
			public void onLocationChanged(Location newLocation) {
				GeoPoint geopoint = new GeoPoint(
						(int) (newLocation.getLatitude() * 1E6), (int) (newLocation
								.getLongitude() * 1E6));
				//createAndShowMyItemizedOverlay(geopoint);
			}
			
 
			public void onProviderDisabled(String arg0) {
			}
 
			public void onProviderEnabled(String arg0) {
			}
 
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			}
		};
		locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				locListener);
 
	}
 
	public void createAndShowMyItemizedOverlay(GeoPoint point) {
		//remove old overlay
		List<Overlay> overlays = myMap.getOverlays();
		if(overlays.size() > 0)
		{
			for(Iterator<Overlay> iterator = overlays.iterator(); iterator.hasNext();)
			{
				iterator.next();
				iterator.remove();
			}
		}
		
		//get the current zip address
		Geocoder geo = new Geocoder(this,Locale.getDefault());
		String zip = null;
		List<Address> addresses;
		try {
			addresses = geo.getFromLocation((double)point.getLatitudeE6() / 1E6, (double)point.getLongitudeE6() / 1E6, 1);
			zip = addresses.get(0).getPostalCode();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 
		// initialize icon
		Drawable icon = getResources().getDrawable(R.drawable.map_pointer);
		icon.setBounds(0,0, icon.getIntrinsicWidth(), icon
				.getIntrinsicHeight());
		
		// create my overlay and show it
		overlay = new MyItemizedOverlay(icon,this);		
		OverlayItem item = new OverlayItem(point, zip, "TEST ME IF YOU DARE");
		overlay.addItem(item);
		myMap.getOverlays().add(overlay);
		
		//animate to the pont
		mc.animateTo(point);
 
		// redraw map
		myMap.postInvalidate();
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
	
	@SuppressWarnings("rawtypes")
	public class MyItemizedOverlay extends ItemizedOverlay {
		
		Context mContext;
		private List<OverlayItem> items;
		private Drawable marker;
		String zip = null;
	 
		public MyItemizedOverlay(Drawable defaultMarker, Context context) {
			super(defaultMarker);
			items = new ArrayList<OverlayItem>();
			marker = defaultMarker;
			mContext = context;
			
		}
	 
		@Override
		protected OverlayItem createItem(int index) {
			return items.get(index);
		}
	 
		@Override
		public int size() {
			return items.size();
	 
		}
	 
		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {
			super.draw(canvas, mapView, shadow);
			boundCenterBottom(marker);
	 
		}
		
		@Override
		public boolean onTap(GeoPoint point, MapView mapView)
		{
			if(super.onTap(point,mapView)) //an overlay was pressed
				return true;
			
			//no overlay was pressed, create a new point
			MyActivity.createAndShowMyItemizedOverlay(point);
			
			  return true;
			
			
		}
		
		@Override
		public boolean onTap(int index) {
			  final OverlayItem item = items.get(index);
       	   if(item.getTitle() == null) //no zip could be generated for this position
    	   {    		   
 			  AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			  builder.setMessage("Could not resolve ZIP at this location. Please try another location.")
		       .setCancelable(true)
		       .setNegativeButton("Ok", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
			  builder.show();
    	   }
       	   else
       	   {
			  AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
			  builder.setTitle("Confirm Location");
			  builder.setMessage("Would you like to set " + item.getTitle() +  " as the observed location?")
		       .setCancelable(true)
		       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   Intent intent = new Intent();
		        	   intent.putExtra("zip", item.getTitle());
		        	   setResult(RESULT_OK,intent);
		                MyActivity.finish();
		           }
		       })
		       .setNegativeButton("No", new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		                dialog.cancel();
		           }
		       });
			  builder.show();
       	   }			  
			  return true;
		}
	 
		public void addItem(OverlayItem item) {
			items.add(item);
			populate();
		}
	 
	}
}
